<template>
  <ZZDialog class="myself" title="图上标绘" @close="onClose()">
    <ul class="toolbar">
      <li id="btn_plot_openfile"><i class="fa fa-folder-open-o" title="打开文件"></i></li>
      <li id="btn_plot_openfile2"><i class="fa fa-folder-open" title="叠加文件"></i></li>
      <li id="btn_plot_savefile"><i class="fa fa-save" title="保存文件"></i></li>
      <li id="btn_plot_delall"><i class="fa fa-trash" title="清空标绘"></i></li>
      <li id="btn_plot_isedit"><i class="fa fa-unlock" title="是否可编辑"></i></li>
    </ul>

    <el-tabs class="demo-tabs">
      <el-tab-pane label="绘制">
        <el-select v-model="value" class="type-select" @change="onChangeSlelct()">
          <el-option v-for="item in plotOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <ul class="plotlist">
          <li v-for="item in CurrentItems" :key="item.name">
            <i>
              <img
                v-if="item.type != 'font-point'"
                :src="item.image"
                :title="item.name"
                @click="onClickItem(item)"
                iconClass="fa fa-flag"
                class="li-item"
              />
              <i
                v-if="item.type == 'font-point'"
                :title="item.name"
                :class="item.style.iconClass"
                style="color: #fafa00"
              ></i>
            </i>
          </li>
        </ul>
      </el-tab-pane>
      <el-tab-pane label="列表">
        <el-table :data="entityListRef">
          <el-table-column prop="type" label="类型" width="90" />
          <el-table-column prop="name" label="名称" width="60" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button-group>
                <el-button link type="primary" size="small" @click.prevent="onEditEntity(scope.$index)">编辑</el-button>
                <el-button link type="primary" size="small" @click.prevent="onDeleteEntity(scope.$index)">
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </ZZDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, markRaw, defineAsyncComponent } from 'vue';
import ZZDialog from '@/common/ZZDialog.vue';
import { useViewer, useDrawcontrol } from '@/stores/viewer';
import { closeComponent, componentIsOpen, openComponent } from '@/common/DzModalService';
import EventBus from '@/common/EventBus';
import { plotItems, plotOptions } from './plotData/plotItem';

let viewer: any;
let drawControl: any;
const plotAttrUrl = '../components/PlotAttr.vue';
const plotAttrVue = defineAsyncComponent(() => import('../components/PlotAttr.vue'));

const value = ref('二维平面类');
let CurrentItems: any = reactive(plotItems.二维平面类);

interface IStyle {
  index: number;
  name: string;
  type: string;
}
const entityListRef = ref<IStyle[]>([]);

const onClickItem = function (it: any) {
  initDrawControl();
  drawControl.hasEdit(true);

  const defStyle = zz3d.draw.util.getDefStyle(it.style);
  const item = Object.assign({ attr: { id: '', name: '', remark: '' } }, defStyle, it);
  drawControl.startDraw(item);
};

const onChangeSlelct = function () {
  const cur = value.value;
  CurrentItems = plotItems[cur];
};

const onDeleteEntity = function (index: any) {
  const entity = drawControl.getEntitys()[index];
  drawControl.deleteEntity(entity);
  updateEntityList();
};

const onEditEntity = function (index: any) {
  const entity = drawControl.getEntitys(true)[index];
  if (entity == null) return;
  viewer.zz.flyTo(entity);
  drawControl.startEditing(entity);
};

const startEdit = function (entity: any) {
  const lonlats = drawControl.getCoordinates(entity);
  const opt = {
    entity: entity,
    lonlats: lonlats
  };

  if (componentIsOpen(plotAttrUrl)) {
    EventBus.emit('editEntity', opt);
  } else {
    openComponent(plotAttrVue, plotAttrUrl, opt);
  }
};

const updateEntityList = function () {
  entityListRef.value.length = 0;
  if (!drawControl) {
    return;
  }

  const tempData = drawControl.toGeoJSON();
  if (!tempData || !tempData.features) {
    return;
  }

  for (let i = 0; i < tempData.features.length; ++i) {
    const feature = tempData.features[i];
    let name;
    let type;
    if (feature.properties) {
      name = (feature.properties.attr && feature.properties.attr.name) || feature.properties.name || '未命名';
      type = feature.properties.type;
    }
    entityListRef.value.push({ index: i, name: name, type: type });
  }
};

const initDrawControl = function () {
  if (drawControl) {
    return;
  }
  if (!viewer) {
    viewer = viewer = useViewer().viewer;
  }
  if (!viewer) {
    return;
  }

  drawControl = new zz3d.Draw(viewer, {
    hasEdit: false,
    nameTooltip: true
  });
  const draw = markRaw(drawControl);
  useDrawcontrol().setDrawcontrol(draw);

  const editCallback = function (e: any) {
    startEdit(e.entity);
  };

  //事件监听
  drawControl.on(zz3d.draw.event.DrawCreated, editCallback);
  drawControl.on(zz3d.draw.event.EditStart, editCallback);
  drawControl.on(zz3d.draw.event.EditMovePoint, editCallback);
  drawControl.on(zz3d.draw.event.EditRemovePoint, editCallback);
  drawControl.on(zz3d.draw.event.EditStop, function (_e: any) {
    closeComponent(plotAttrUrl);
    updateEntityList();
  });

  drawControl.on(zz3d.draw.event.Delete, function (_e: any) {
    // sendDeleteEntity(e.entity);//保存数据
    // showTable();
    updateEntityList();
  });

  const plotLayer = {
    pid: -1,
    name: 'plot-layer',
    visible: true,
    type: 'base',
    onAdd: function () {
      //显示回调
      drawControl.setVisible(true);
    },
    onRemove: function () {
      //隐藏回调
      drawControl.setVisible(false);
    },
    onCenterAt: function (duration: number) {
      //定位回调
      const arr = drawControl.getEntitys();
      viewer.flyTo(arr, {
        duration: duration
      });
    },
    compare: {
      //"分屏对比" 中使用, 会覆盖上面方法
      onCreate: function (_viewerEx: any) {
        // viewerEx为分屏中另外一个屏的地球回调 ，add时不能讲当前viewer的对象直接添加到viewerEx，需要新构造
        // drawControlEx = new zz3d.Draw(viewerEx, { hasEdit: false, nameTooltip: true })
      },
      onAdd: function (_viewerEx: any) {
        //显示回调
        // viewerEx为分屏中另外一个屏的地球回调
        // drawControlEx.loadJson(that.getGeoJson()); //新构造数据，不能直接add到新viewerEx
        // drawControlEx.setVisible(true);
      },
      onRemove: function (_viewerEx: any) {
        //隐藏回调
        // drawControlEx.setVisible(false);
      }
    }
  };

  zz3d.layer.createLayer(plotLayer, viewer);
  viewer.zz.addOperationalLayer(plotLayer);
  // drawControl.hasEdit(true);
  EventBus.emit('sceneLoaded', {});
};

// 初始化调用
onMounted(async () => {
  viewer = useViewer().viewer;
  drawControl = useDrawcontrol().drawcontrol;

  if (!viewer) return;
  initDrawControl();
  drawControl.hasEdit(true);
  updateEntityList();
});

const onClose = function () {
  drawControl.stopDraw();
  drawControl.hasEdit(false);
};
</script>

<style scoped>
.myself {
  position: absolute;
  left: calc(100% - 250px);
  top: 50px;
  min-width: 100px;
  height: 800px;
  width: 236px;
}

.li-item {
  width: 50px;
  height: 50px;
  margin: 4px 8px 4px 0px;
}

.li-item:hover {
  border: 1px solid rgb(32, 160, 255);
}

.plotlist {
  display: flex;
  width: 236px;
  padding: 2px 4px 2px 0px;
  flex-direction: row;
  flex-wrap: wrap;
  margin-top: 4px;
}

.plotlist i {
  width: 50px;
  height: 50px;
  margin: 0px;
}

.type-select {
  padding: 0px 4px 0px 0px;
  width: 100%;
}

.demo-tabs {
  padding-left: 4px;
}
</style>

<style scoped src="./toolbar.css"></style>
